﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using ZLCMS.Business.Util;
using System.Web.Security;

namespace ZLCMS.Web.SystemManage.Basics.Shop.Member
{
    public partial class MemberDetail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //页面控件数据

            if (!IsPostBack)
            {
                //todo 设置页面控件信息

                int uid = 0;
                try
                {
                    uid = Int32.Parse(Request["uid"]);
                }
                catch
                {

                }
                MemberInfo item = null;
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    item = session.Get<MemberInfo>(uid);
                    if (item != null)
                    {
                        //保存uid
                        ViewState["uid"] = uid;
                    }
                    else
                    {
                        item = new MemberInfo();
                    }

                    ddl_level.DataSource = session.CreateQuery("from MemberLevelDef order by Sort").List<MemberLevelDef>();
                }
                
                //在此设置控件的初始属性
                account.Text = item.AccountId;
                memberName.Text = item.MemberName;
                email.Text = item.Email;
                phone.Text = item.Phone;
                score.Text = string.Format("{0}", item.Score);

                ddl_level.DataValueField = "LevelId";
                ddl_level.DataTextField = "Name";
                ddl_level.DataBind();
                ddl_level.SelectedValue = item.Level.ToString();
                wxopenid.Text = item.WxOpenId;
                remarks.Text = item.Remarks;
                owner.Text = item.OwnerAccount;
            }
            else
            {
                //todo 保存数据
                ZLCMS.Business.DwzFrame.FrameHelper _framePage = new ZLCMS.Business.DwzFrame.FrameHelper(this);


                //框架返回成功提示
                ZLCMS.Business.DwzFrame.ReturnCode rc = new ZLCMS.Business.DwzFrame.ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功"
                };

                int uid = ViewState["uid"] == null ? 0 : (int)ViewState["uid"];
                MemberInfo item = null;
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    item = session.Get<MemberInfo>(uid);
                    if (item == null)
                    {
                        item = new MemberInfo();
                        item.OwnerAccount = UserKit.GetUserAccountFailLogin();
                        item.AddDate=DateTime.Now;
                        item.Birthday = DateTime.Now;
                        item.LastLog = DateTime.Now;
                    }
                    else
                    {
                         if (item.Score != Convert.ToInt32(score.Text))
                        {
                            //管理员修改了积分 ,添加记录
                            session.Save(new MemberScoreLog()
                            {
                                MemberAccount = item.AccountId,
                                Score = Convert.ToInt32(score.Text),
                                FinalScore = Convert.ToInt32(score.Text),
                                Remark = "管理员修改积分为:" + score.Text,
                                OwnerAccount = item.OwnerAccount,
                                OptTime = DateTime.Now,
                                ScoreType = "modify"
                            });
                        }
                    }

                    //在此设置item的各个属性

                    //检查帐号是否存在
                    if (item.AccountId != account.Text)
                    {
                        int cnt = Convert.ToInt32(session.CreateSQLQuery("select count(*) from member_info where  account_id=:acc").
                            SetParameter("acc", account.Text).
                            UniqueResult());
                        if (cnt > 0)
                        {
                            rc = new ZLCMS.Business.DwzFrame.ReturnCode()
                            {
                                statusCode = 300,
                                message = "帐号已存在"
                            };

                            _framePage.Alert(rc);
                            return;
                        }
                        item.AccountId = account.Text;

                    }

                    //检查帐号是否存在
                    if (!string.IsNullOrEmpty(phone.Text) && item.Phone != phone.Text)
                    {
                        int cnt = Convert.ToInt32(session.CreateSQLQuery("select count(*) from member_info where  telephone=:phone").
                            SetParameter("phone", phone.Text).
                            UniqueResult());
                        if (cnt > 0)
                        {
                            rc = new ZLCMS.Business.DwzFrame.ReturnCode()
                            {
                                statusCode = 300,
                                message = "手机已存在"
                            };

                            _framePage.Alert(rc);
                            return;
                        }
                        item.Phone = phone.Text;

                    }
                    item.MemberName = memberName.Text;
                    item.Email = email.Text;
                    try
                    {
                        item.Score = Convert.ToInt32(score.Text);
                    }
                    catch (System.Exception ex)
                    {
                    }
                    item.Level = int.Parse(ddl_level.SelectedValue);
                    item.OwnerAccount = owner.Text;
                    item.WxOpenId = wxopenid.Text;
                    item.Remarks = remarks.Text;
                    
                    //保存并更新item
                    session.SaveOrUpdate(item);

                    session.Flush();
                }


                rc.callbackType = "forward";
                rc.forwardUrl = "/SystemManage/Basics/Shop/Member/MemberDetail.aspx?tabid=MemberDetail";

                if (Request["submit_op"] != "1")
                {
                    rc.forwardUrl += "&uid=" + item.Id;
                }

                _framePage.Alert(rc);
            }
        }
    }
}